<template>
  <view>
    <form>
      <xmInfo
      :projectno="dataInfo.projectno"
      :projectname="dataInfo.name"
    ></xmInfo>
      <view class="cu-form-group">
        <view class="title"><text class="cuIcon-kb text-xs text-red"></text>安装人员</view>
        <view>{{ dataInfo.pername  }}</view>
      </view>
      <view class="cu-form-group">
        <view class="title"><text class="cuIcon-kb text-xs text-red"></text>安装人员编号</view>
        <view>{{ dataInfo.perno  }}</view>
      </view>
      <view class="cu-form-group">
        <view class="title"><text class="cuIcon-favorfill text-xs text-red"></text>申请挂表时间</view>
        <!-- <view>{{ dataInfo.installtime }}</view> -->
        <picker mode="date" :value="dataInfo.installtime"  @change="DateChange($event)" >
          <view class="picker"> {{ dataInfo.installtime ? dataInfo.installtime : "请选择申请挂表时间" }}</view>
        </picker>
      </view>
      <view class="cu-form-group" style="min-height: 0"></view>
      <view class="cu-bar bg-white">
        <view class="action"><text class="cuIcon-favorfill text-xs text-red"></text>申请说明</view>
      </view>
      <view class="cu-form-group">
        <textarea
            maxlength="-1"
            v-model="dataInfo.remarks"
            @input="textareaAInput($event)"
            placeholder="请输入申请说明"
          ></textarea>
      </view>

      <view class="cu-form-group" style="min-height: 0"></view>
      <view class="cu-bar bg-white">
        <view class="action"><text class="cuIcon-favorfill text-xs text-red"></text>挂表申请图片(需上传3张图片)</view>
      </view>
      <view class="cu-form-group">
        <js-uploadfile  v-model="dataInfo.dataMap"  :biz-key="dataInfo.id"   biz-type="PmWaterMeter_image" ></js-uploadfile>
      </view>
      <view style="height: 180rpx" v-if="flag"></view>
      <view class="btn-group cu-bar foot cu-bar1" v-if="flag">
        <view class="flex">
            <js-bpm-button
          v-model="dataInfo.bpm"
          :biz-key="dataInfo.id"
          form-key="Flow_PmWaterMeter"
          @complete="submit"
        ></js-bpm-button>
        </view>
      </view>
    </form>

  </view>
</template>
<script>
import xmInfo from "@/pages/zfgs/index/componetns/xmInfo.vue";
import {hasPermission} from '@/common/fire.js'
export default {
  components: {
    xmInfo
  },
  data() {
    return {
      uploadOptions: {},
      switchA: false,
      date: new Date().toISOString().substring(0, 10),
      modalName: null,
      modalNameDetail: null,
      showAddDetail: false,
      dataInfo: {
        id: "",
        bpm: {},
        dataMap:{
          
        }
      },
      isSubmitting: false,
      showButton: true,
      flag: hasPermission('btn:add:guabiao'),
      x: 650, //x坐标
      y: 650, //y坐标
    };
  },
  onLoad(e) {
    console.log(e,'e====');
    if (!!e.id) {
      this.getPmWatermeterForm(e.id);
    }
    if (!!e.xm) {
      this.showButton = true;
      this.dataInfo = JSON.parse(e.xm);
      this.dataInfo.pername = this.vuex_user.userName;
      this.dataInfo.perno = this.vuex_user.loginCode;
      this.dataInfo.status = 4;
    }

  },
  methods: {
    submit() {
      if(!this.dataInfo.installtime){
        this.$u.toast("挂表申请时间必选");
        return;
      }
      if(!this.dataInfo.remarks){
        this.$u.toast("申请说明必填");
        return;
      }
	  console.log(this.dataInfo);
      if (!this.dataInfo.dataMap || !this.dataInfo.dataMap.PmWaterMeter_image) {
        this.$u.toast("挂表申请图片必传");
        return;
      }else{
		let arr = this.dataInfo.dataMap.PmWaterMeter_image.split(',');
		if (arr.length != 3) {
		    this.$u.toast("请上传3张图片");
			return;
		} 
	  }
      if (this.isSubmitting) {
        return;
      } else {
        this.isSubmitting = true;
        try {
			    this.dataInfo.status = 4;
          this.$u.api.zfgs
            .pmWatermeterSave(this.dataInfo)
            .then((res) => {
              if (res.result == "true") {
                this.$u.toast(res.message);
                const itemContent = {
                  projectno: this.dataInfo.projectno,
                  projectname: this.dataInfo.projectname , 
                };
                setTimeout(() => {
                  // uni.navigateTo({
                  //   url:
                  //     "/pages/zfgs/process/meter/pmWatermeter/list?item=" +
                  //     JSON.stringify(itemContent),
                  // });
				  uni.navigateBack({
				      delta: 1,
				  });
                }, 500);
              }else{
                this.$u.toast(res.message);
              }
            });
        } catch (error) {
          this.$u.toast(error.message);
        } finally {
          this.isSubmitting = false;
        }
      }
    },

    getPmWatermeterForm(id) {
      this.$u.api.zfgs
        .pmWatermeterForm({
          id: id,
        })
        .then((res) => {
          console.log(res, "res===");
          this.dataInfo = res.pmWatermeter;
          this.dataInfo.projectname = res.pmWatermeter.name;
        });
    },
    SwitchA(e) {
      // this.switchA = e.detail.value
    },
    DateChange(e) {
      console.log(e,'e====');
      this.dataInfo.installtime = e.detail.value;
      this.$forceUpdate();
    },
    textareaAInput(e) {
      this.dataInfo.remarks = e.detail.value;
    },
    addDetail() {
      this.showAddDetail = true;

      this.modalNameDetail = "DrawerModalR";

      console.log(this.modalNameDetail);
    },
    modalNameDetailEmit(e) {
      this.modalNameDetail = e;
    },
    async checkedListEmit(e) {
      console.log(e, "checkedListEmit", this.dataInfo);
      if (!this.dataInfo.pmMaterialchecksList) {
        this.dataInfo.pmMaterialchecksList = [];
      }

      // 将 e 中的每个项目转换为所需格式

      let eArray = [];
      e.forEach((item) => {
        eArray.push({
          pmid: item.id,
          metercode: item.mcode,
          metername: item.mname,
          mstd: item.mstd
        });
      });

      if (this.dataInfo.pmMaterialchecksList.length == 0) {
        this.dataInfo.pmMaterialchecksList = eArray;
      } else {

      // 创建一个新数组用于存放最终结果
        let newArray = [];

        // 遍历原始数据
        this.dataInfo.pmMaterialchecksList.forEach((originalItem) => {
          let matched = false; // 标记是否找到了匹配项

          // 遍历eArray
          eArray.forEach((updateItem) => {
            if (originalItem.pmid === updateItem.pmid) {
              // 找到匹配项，标记并保存更新后的项目
              matched = true;
              newArray.push(updateItem);
            }
          });

          // 如果没有在eArray中找到匹配项，则保留原始项目
          if (!matched) {
            newArray.push(originalItem);
          }
        });

        // 将eArray中未在原始列表中找到匹配pmid的项追加到newArray
        eArray.forEach((itemFromEArray) => {
          let exists = newArray.some((item) => item.pmid === itemFromEArray.pmid);
          if (!exists) {
            newArray.push(itemFromEArray);
          }
        });

        // 最后，将处理后的数组赋值回原对象
        this.dataInfo.pmMaterialchecksList = newArray;    

      }



    },

    ViewImage(imageList, e) {
      uni.previewImage({
        urls: imageList,
        current: e.currentTarget.dataset.url,
      });
    },
    ChooseImage() {
      uni.chooseImage({
        count: 4, //默认9
        sizeType: ["original", "compressed"], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ["album"], //从相册选择
        success: (res) => {
          if (this.dataInfo.dImageList.length != 0) {
            this.dataInfo.dImageListst = this.dataInfo.dImageList.concat(
              res.tempFilePaths
            );
          } else {
            this.dataInfo.dImageList = res.tempFilePaths;
          }

          console.log(this.dataInfo, "this.dataInfo");
          this.$u.toast("上传成功");
        },
      });
    },
  },
};
</script>
<style lang="scss" scoped>
$all_width: 140rpx;
$all_height: 140rpx;
.movable-area {
  z-index: 999;
  height: 97vh;
  width: 650rpx;
  // max-width: 1152rpx;
  // 固定在右边
  top: -150rpx;
  position: fixed;
  right: $all_width;
  // 固定在右下角
  pointer-events: none; //此处要加，鼠标事件可以渗透
  .movable-view {
    width: $all_width;
    height: $all_height;
    pointer-events: auto; //恢复鼠标事件
    .cu-bar{
      width: 320rpx;
    }
  }
}
.action {
  color: #303133;
}
.cu-form-group {
  flex-wrap: wrap;
}
.text-sl {
  font-size: 22px !important;
}
.cu-bar1 {
  min-height: 80px;
}
.cu-btn {
  font-size: 16px;
  height: 40px;
}
.foot {
  z-index: 997;
  background: #fff;
}
.green {
  color: green;
}
.input-align {
  text-align: right;
}
.sub-title{
  flex-grow: 1; /* 让右侧内容占据剩余空间 */
  max-width: 200px; /* 或其他合适的最大宽度，超过这个宽度时内容会换行 */
  word-break: break-word; /* 或 overflow-wrap: break-word; 允许单词在必要时断开以适应宽度 */
}
.xm-title{
  flex-basis: 100px; /* 或其他合适的固定宽度，用于左侧标题 */
  flex-shrink: 0; /* 防止标题在小屏幕下收缩 */
  overflow: hidden; /* 可选，防止内容溢出 */
}
.text-xsl {
  font-size: 60rpx !important;
}
.flex-end {
  display: flex;
  justify-content: flex-end;
}
.text-xs {
  font-size: 18rpx !important;
}
.title{
  flex-grow: 1; /* 让右侧内容占据剩余空间 */
  max-width: 240rpx; /* 或其他合适的最大宽度，超过这个宽度时内容会换行 */
  word-break: break-word; /* 或 overflow-wrap: break-word; 允许单词在必要时断开以适应宽度 */
}
.cuIcon-kb::before {
    // content 为空白
    display: inline-block;
    content: ' ';
    width: 18rpx;
    height: 100%;
    
}
</style>